package com.kamfu.bio.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

/**
 * @program: kamfu
 * @ClassName BioServer1
 * @description:基于线程池的多客户端实现
 * @author: liandy
 * @create: 2021-12-30 10:23
 * @Version 1.0
 **/
public class BioThreadPoolServer {
    public static void main(String[] args) {
        try {
            //新建一个线程池
            ThreadPool threadPool=new ThreadPool();
            //1.建立ServerSocket监听本地端口
            ServerSocket serverSocket=new ServerSocket(9000);
            while (true){
                //2.等待客户端连接，程序将处于阻塞状态
                Socket socket = serverSocket.accept();
                System.out.println("新的客户端连接成功");
                //将socket移交给线程池处理
                threadPool.execute(new SocketThread(socket));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
class ThreadPool{
    private ExecutorService executorService;
    public ThreadPool(){
        executorService = new ThreadPoolExecutor(3, 5, 120,
                TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10));
    }

    public void execute(Runnable runnable){
        this.executorService.execute(runnable);
    }

}